package com.appspot.zarm.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.zarm.game.GamesStorage;
import com.appspot.zarm.game.User;

public class Dispatcher extends HttpServlet {

	private static final long serialVersionUID = 7581075472706864451L;

	/**
	 * Action values
	 */
	public static final String ACTION_PARAM = "action";
	public static final String DATA_PARAM = "data";
	
	public static final String INIT_PARAM = "init";
	public static final String JOIN_ID_PARAM = "joinId";
	public static final String MULTIPLAYER_PARAM = "multiplayer";
		
	/**
	 * Constants
	 */
	private static final String GAMES_STORAGE_ATTR_NAME = "GamesStorage";
	
	/**
	 * Variables
	 */
	
	private String message = "";

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		// action and game data
		String action = (String) request.getParameter(ACTION_PARAM);
		String data = (String) request.getParameter(DATA_PARAM);
		boolean isMultiplayer = (String) request.getParameter(MULTIPLAYER_PARAM) != null;

		// join second player to existing game
		String joinId = (String) request.getParameter(JOIN_ID_PARAM);

		// action processing
		if (action != null) {
			
			String userId = request.getSession().getId();
			User user = new User(userId);
			
//			if (isMultiplayer) {
//				message = "Use this id for second player to join the game " + user.getId();
//			}

			GameAction gameAction = new GameActionFactory().getGameAction(GameActionFactory.GOMOKU);
			GamesStorage gs = getGamesStorage();
			String result = gameAction.process(gs, user, action, data, message, isMultiplayer, joinId);

			// return result to the callback javascript method
			if (result != null && joinId == null) {
				print(response, result);
			} else {
				goLayoutPage(request, response);
			}

		} else {
			// action is absent so only refresh layout page 
			goLayoutPage(request, response);
		}
	}

	private GamesStorage getGamesStorage() {
		GamesStorage gs = (GamesStorage) getServletContext().getAttribute(GAMES_STORAGE_ATTR_NAME);
		if (gs == null) {
			gs = new GamesStorage();
			getServletContext().setAttribute(GAMES_STORAGE_ATTR_NAME, gs);
		}
		return gs;
	}

	private void goLayoutPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		getServletConfig().getServletContext().getRequestDispatcher("/layout.jsp").forward(request, response);
	}

	private void print(HttpServletResponse response, String value) throws IOException {
		response.setContentType("text/html");
		PrintWriter pw = response.getWriter();
		pw.print(value);
	}

}
